﻿using System;
using System.Windows;
using System.Windows.Controls;
namespace TciNewsReader_2014_04.Behaviours
{   // Credit:   http://stackoverflow.com/users/1727/samuel-jack
    public static class WebBrowserBehaviour
    {   // binding fix:  http://stackoverflow.com/questions/263551/databind-the-source-property-of-the-webbrowser-in-wpf
        // cyrillic fix: http://social.msdn.microsoft.com/Forums/vstudio/en-US/88ee627f-7281-4cee-96e9-53d3a8a3b7cb/problem-with-encoding-in-webbrowser-when-using-navigatetostring?forum=wpf
        public static readonly DependencyProperty BindableSourceProperty =
            DependencyProperty.RegisterAttached("BindableSource", typeof(object), typeof(WebBrowserBehaviour), new UIPropertyMetadata(null, BindableSourcePropertyChanged));
        public static object GetBindableSource(DependencyObject obj)
        {
            return obj.GetValue(BindableSourceProperty);
        }
        public static void SetBindableSource(DependencyObject obj, object value)
        {
            obj.SetValue(BindableSourceProperty, value);
        }
        public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            WebBrowser browser = o as WebBrowser;
            if (browser == null) return;
            Uri uri = null;
            if (e.NewValue is string)
            {
                var uriString = e.NewValue as string;
                if (Uri.IsWellFormedUriString(uriString, UriKind.Absolute))
                {
                    uri = string.IsNullOrWhiteSpace(uriString) ? null : new Uri(uriString);
                }
                else
                {
                    if (String.IsNullOrEmpty(uriString))
                    {
                        uriString = " ";
                    }
                    var html = "<html><head><meta http-equiv='Content-Type' content='text/html;charset=UTF-8'></head><body>" + uriString + "</body></html>";
                    browser.NavigateToString(html);
                    return;
                }
            }
            else if (e.NewValue is Uri)
            {
                uri = e.NewValue as Uri;
            }
            browser.Source = uri;
        }
    }
}
